package com.wmyg.antifake.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wmyg.antifake.dto.QueryDto;
import com.wmyg.antifake.entity.*;
import com.wmyg.antifake.fabric.FabricDao;
import com.wmyg.antifake.fabric.dto.QueryFabricDto;
import com.wmyg.antifake.fabric.vo.BatchVo;
import com.wmyg.antifake.fabric.vo.HistoryFabricVo;
import com.wmyg.antifake.fabric.vo.TrackFabricVo;
import com.wmyg.antifake.gs1.GS1Result;
import com.wmyg.antifake.gs1.GS1Utils;
import com.wmyg.antifake.gs1.ns2.TSDBasicProductInformationModule;
import com.wmyg.antifake.gs1.ns2.basic.Link;
import com.wmyg.antifake.gs1.ns2.basic.StringAVP;
import com.wmyg.antifake.repository.*;
import com.wmyg.antifake.service.QueryService;
import com.wmyg.antifake.utils.ProductHashUtil;
import com.wmyg.antifake.utils.TsStringCreator;
import com.wmyg.antifake.varaes.sbox.SboxCreator;
import com.wmyg.antifake.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 王卓逸
 * @program TODO
 * @description TODO
 * @create 2019-05-12
 */
@Slf4j
@Service
public class QueryServiceImpl implements QueryService {

    private final static String QRCODE_PREFIX = "https%3A%2F%2Fmiaomark.cn%2Fr%3Fi%3D";

    @Autowired
    WxUserRepository wxUserRepository;

    @Autowired
    FabricDao fabricDao;

    @Autowired
    ProductRepository productRepository;

    @Autowired
    WxRecordRepository wxRecordRepository;

    @Autowired
    CompanyRepository companyRepository;

    @Autowired
    FactoryRepository factoryRepository;

    @Autowired
    ProductOriginRepository productOriginRepository;

    @Autowired
    GsOneRepository gsOneRepository;

    @Override
    public Message trackQrCode(QueryDto queryDto) {
        TrackInfoVo trackInfo = new TrackInfoVo();
        trackInfo.setQrUrl("https://minip.weimengyungu.cn/antifake/track/qr.do?qR=" + queryDto.getItemNo());
        trackInfo.setType(queryDto.getType());
        trackInfo.setItemNo(queryDto.getItemNo());
        Integer userId = 0;
        WxUser user = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //1.判断是否有openid或者伪id，二者皆无，创建伪id，保存新用户对象，并返回伪id，二者有一，查出userId
        if (StringUtils.isBlank(queryDto.getOpenid()) && StringUtils.isBlank(queryDto.getProvisionalId())) {
            user = new WxUser();
            String provisionalId = queryDto.getItemNo() + UUID.randomUUID().toString();
            user.setProvisionalId(provisionalId);
            wxUserRepository.save(user);
            log.info("Create a new user {}", user);
            userId = user.getUserId();
            trackInfo.setProvisionalId(provisionalId);
        } else {
            user = wxUserRepository.findByProvisionalId(queryDto.getProvisionalId());
            if (null == user) {
                user = new WxUser();
                user.setProvisionalId(queryDto.getProvisionalId());
                wxUserRepository.save(user);
            }
            userId = user.getUserId();
            trackInfo.setProvisionalId(user.getProvisionalId());
        }
        //判断二维码是否匹配设定格式
        if (queryDto.getItemNo().contains(QRCODE_PREFIX)) {
            String itemNo = queryDto.getItemNo().substring(queryDto.getItemNo().indexOf(QRCODE_PREFIX) + QRCODE_PREFIX.length());
            queryDto.setItemNo(itemNo);
            trackInfo.setItemNo(itemNo);
        }
        if (!queryDto.getItemNo().matches("^[(]01[)]\\d{14}[(]10[)]\\d{6}[(]21[)][A-Z0-9]{18}$")) {
            log.info("The qrcode {} is not match", queryDto.getItemNo());
            return new Message(3, trackInfo);
        }
        String productId = queryDto.getItemNo().substring(5, queryDto.getItemNo().indexOf("(10)"));
        Product product = productRepository.findByProductId(productId);
        String productHash = ProductHashUtil.hashProduct(product);
        QueryFabricDto queryFabricDto = new QueryFabricDto();
        queryFabricDto.setAddress(queryDto.getAddress());
        queryFabricDto.setQueryTime(queryDto.getQueryTime());
        queryFabricDto.setLongitude(queryDto.getLongitude());
        queryFabricDto.setLatitude(queryDto.getLatitude());
        queryFabricDto.setUserId(userId);
        queryFabricDto.setUserAgent(queryDto.getUserAgent());
        queryFabricDto.setClientIp(queryDto.getClientIp());
        queryFabricDto.setProductHash(productHash);
        //2.根据查询类型选择fabric方法，并与fabric交互
        TrackFabricVo trackFabricVo = null;
        if (queryDto.getQueryType() == 0) {
            trackFabricVo = fabricDao.queryAndInvoke("NewQueryMethod", queryDto.getItemNo(), queryFabricDto, TrackFabricVo.class);
        } else {
            trackFabricVo = fabricDao.query("NewQueryMethod", queryDto.getItemNo(), TrackFabricVo.class);
        }
        //3.二维码校验、分析
        log.info("Get data from fabricDao is {}", trackFabricVo);
        if (null == trackFabricVo) {
            return new Message(2, trackInfo);
        }
        if (checkAndParseTrackInfo(queryDto.getItemNo(), trackInfo, trackFabricVo)) {
            log.info("The matchType of {} is {}", queryDto.getItemNo(), trackInfo.getMatchType());
            if (queryDto.getQueryType() == 0) {
                //4.存储查询记录
                WxRecord wxRecord = new WxRecord();
                wxRecord.setRecordCode(queryDto.getItemNo());
                wxRecord.setAddress(StringUtils.isBlank(queryDto.getAddress()) ? queryDto.getClientIp() : queryDto.getAddress());
                wxRecord.setQueryTime(queryDto.getQueryTime());
                wxRecord.setProductName(trackFabricVo.getProductName());
                wxRecord.setCollected(0);
                user.getRecords().add(wxRecord);
                wxUserRepository.save(user);
                List<WxRecord> wxRecords= wxUserRepository.findById(user.getUserId()).get().getRecords();
                for (WxRecord w :
                        wxRecords) {
                    if (wxRecord.getQueryTime().equals(w.getQueryTime())) {
                        trackInfo.setRecordId(w.getRecordId());
                    }
                }
                //5.继续拼装返回值
                trackInfo.setAddress(StringUtils.isBlank(queryDto.getAddress()) ? queryDto.getClientIp() : queryDto.getAddress());
                trackInfo.setQueryTime(sdf.format(queryDto.getQueryTime()));
            } else {
                WxRecord wxRecord = wxRecordRepository.findByRecordId(queryDto.getRecordId());
                trackInfo.setAddress(wxRecord.getAddress());
                trackInfo.setQueryTime(sdf.format(wxRecord.getQueryTime()));
                trackInfo.setRecordId(wxRecord.getRecordId());
            }
            ProductVo productVo = new ProductVo();
            productVo.setProductId(trackFabricVo.getProductId());
            productVo.setProductName(trackFabricVo.getProductName());
            if (StringUtils.isNotBlank(trackFabricVo.getProductLogo())) {
                productVo.setProductLogo(new PictureVo(trackFabricVo.getProductLogo()));
            }
            if (StringUtils.isNotBlank(trackFabricVo.getProductPics())) {
                String[] productPics = trackFabricVo.getProductPics().split(",");
                for (String productPic :
                        productPics) {
                    productVo.getProductPics().add(new PictureVo(productPic));
                }
            }
            if (StringUtils.isNotBlank(product.getOthers())) {
                LinkedHashMap<String, String> map = JSON.parseObject(product.getOthers(), LinkedHashMap.class);
                productVo.setProfessionalInfo(map);
            }
            trackInfo.setProduct(productVo);
            Company company = companyRepository.findByCompanyId(trackFabricVo.getCompanyId());
            CompanyVo companyVo = new CompanyVo();
            companyVo.setCompanyId(company.getCompanyId());
            companyVo.setCompanyName(company.getCompanyName());
            if (StringUtils.isNotBlank(company.getCompanyPics())) {
                String[] companyPics = company.getCompanyPics().split(",");
                for (String companyPic :
                        companyPics) {
                    companyVo.getCompanyPics().add(new PictureVo(companyPic));
                }
            }
            trackInfo.setCompany(companyVo);
            if (null != trackFabricVo.getFactoryId()) {
                Factory factory = factoryRepository.findByFactoryId(trackFabricVo.getFactoryId());
                if (null != factory) {
                    FactoryVo factoryVo = new FactoryVo();
                    factoryVo.setFactoryId(factory.getFactoryId());
                    factoryVo.setFactoryName(factory.getFactoryName());
                    if (StringUtils.isNotBlank(factory.getFactoryPics())) {
                        String[] factoryPics = factory.getFactoryPics().split(",");
                        for (String factoryPic :
                                factoryPics) {
                            factoryVo.getFactoryPics().add(new PictureVo(factoryPic));
                        }
                    }
                    trackInfo.setFactory(factoryVo);
                }
            }
            if (null != trackFabricVo.getOriginId()) {
                ProductOrigin origin = productOriginRepository.findByOriginId(trackFabricVo.getOriginId());
                if (null != origin) {
                    OriginVo originVo = new OriginVo();
                    originVo.setOriginId(origin.getOriginId());
                    originVo.setOriginInfo(origin.getOriginInfo());
                    trackInfo.setOrigin(originVo);
                }
            }
            //整理终端历史查询记录
            Map<Integer, Integer> countMap = new HashMap<>();
            for (HistoryFabricVo history :
                    trackFabricVo.getHistories()) {
                if (!countMap.containsKey(history.getUserId())) {
                    countMap.put(history.getUserId(), 1);
                }
            }
            trackInfo.setTimes(trackFabricVo.getHistories().size());
            Collections.reverse(trackFabricVo.getHistories());
            Integer pers = countMap.size();
            trackInfo.setPers(pers);
            if (pers > 20) {
                Map<String, List<HistoryVo>> historiesMap = trackInfo.getHistories();
                historiesMap.put("me", new ArrayList<>());
                historiesMap.put("others", new ArrayList<>());
                LinkedHashMap<Integer, HistoryVo> othersMap = new LinkedHashMap<>();
                for (HistoryFabricVo history :
                        trackFabricVo.getHistories()) {
                    if (userId.equals(history.getUserId())) {
                        log.info("find the history of me {}", history);
                        historiesMap.get("me").add(new HistoryVo(history.getUserId(), sdf.format(history.getQueryTime()),
                                StringUtils.isBlank(history.getAddress()) ? history.getClientIp() : history.getAddress()));
                    } else {
                        log.info("find the history of others {}", history);
                        othersMap.put(history.getUserId(), new HistoryVo(history.getUserId(), sdf.format(history.getQueryTime()),
                                StringUtils.isBlank(history.getAddress()) ? history.getClientIp() : history.getAddress()));
                    }
                }
                Iterator<Map.Entry<Integer, HistoryVo>> iterator = othersMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<Integer, HistoryVo> entry = iterator.next();
                    historiesMap.get("others").add(entry.getValue());
                }
                trackInfo.setHistoryType(true);
            } else {
                Map<String, List<HistoryVo>> historiesMap = trackInfo.getHistories();
                historiesMap.put("me", new ArrayList<>());
                for (HistoryFabricVo history :
                        trackFabricVo.getHistories()) {
                    if (userId.equals(history.getUserId())) {
                        log.info("find the history of me {}", history);
                        historiesMap.get("me").add(new HistoryVo(history.getUserId(), sdf.format(history.getQueryTime()),
                                StringUtils.isBlank(history.getAddress()) ? history.getClientIp() : history.getAddress()));
                    } else {
                        String key = "other" + history.getUserId();
                        log.info("find the history of {} {}", key, history);
                        if (!historiesMap.containsKey(key)) {
                            historiesMap.put(key, new ArrayList<>());
                        }
                        historiesMap.get(key).add(new HistoryVo(history.getUserId(), sdf.format(history.getQueryTime()),
                                StringUtils.isBlank(history.getAddress()) ? history.getClientIp() : history.getAddress()));
                    }
                }
                trackInfo.setHistoryType(false);
            }
            trackInfo.setIsHistory(null == company.getIsHistory() || company.getIsHistory() == 0);
            //根据历史记录设置提示语
            if (product.getPolicies().isEmpty()) {
                trackInfo.setLevel(1);
                trackInfo.setReminder("属于正常范围");
            } else {
                NoticePolicy[] noticePolicies = product.getPolicies().toArray(new NoticePolicy[product.getPolicies().size()]);
                Integer[] noticeValue = new Integer[product.getPolicies().size()];
                Integer resultIndex = 0;
                for (int i = 0; i < noticePolicies.length; i++) {
                    noticeValue[i] = chechNoticePolicy(trackInfo, noticePolicies[i]);
                    if (noticeValue[i] > noticeValue[resultIndex]) {
                        resultIndex = i;
                    }
                }
                switch (noticeValue[resultIndex]) {
                    case 3:
                        trackInfo.setLevel(3);
                        trackInfo.setReminder(noticePolicies[resultIndex].getDangerContent());
                        break;
                    case 2:
                        trackInfo.setLevel(2);
                        trackInfo.setReminder(noticePolicies[resultIndex].getWarningContent());
                        break;
                    case 1:
                        trackInfo.setLevel(1);
                        trackInfo.setReminder(noticePolicies[resultIndex].getNormalContent());
                        break;
                    default:
                }
            }
            trackInfo.setTotalTimes(wxRecordRepository.count());
            trackInfo.setProductCollectedTimes(wxRecordRepository.countByCollectedAndRecordCodeLike(1, "%" + trackFabricVo.getProductId() + "%"));
            return new Message(0, trackInfo);
        }
        return new Message(1, trackInfo);
    }

    @Override
    public Message trackEanCode(QueryDto queryDto) {
        return trackEan(queryDto);
    }

    private Boolean checkAndParseTrackInfo(String itemNo, TrackInfoVo trackInfoVo, TrackFabricVo trackFabricVo) {
        if (null == trackFabricVo || null == trackFabricVo.getIsValid() || (!trackFabricVo.getIsValid())) {
            log.error("The data is not valid because {}", trackFabricVo.getIsValid());
            return false;
        }
        //1.拆解二维码
        String picLevel = itemNo.substring(34, 35);
        String serial = itemNo.substring(35);
        //2.解密序列号
        String trueSerial = SboxCreator.decrypt(serial, trackFabricVo.getSecretKey());
        Integer partOne = TsStringCreator.parseString(trueSerial.substring(0,5),5);
        Integer partTwo = TsStringCreator.parseString(trueSerial.substring(5,10),5);
        Integer partThr = TsStringCreator.parseString(trueSerial.substring(10),5);
        log.info("The qr is part of {} {} {} {} {} {} {}", itemNo, picLevel, serial, trueSerial, partOne, partTwo, partThr);
        //3.根据包装级别校验二维码
        switch (picLevel) {
            case "X":
                if (partOne!=0) {
                    return false;
                }
                if (partTwo > trackFabricVo.getCaseNum()) {
                    return false;
                }
                if (!partThr.equals(trackFabricVo.getBoxNum())) {
                    return false;
                } else if (partThr != 0) {
                    trackInfoVo.setPackInfo(partThr + "盒/箱");
                } else {
                    trackInfoVo.setPackInfo(trackFabricVo.getProductSpecs());
                    trackInfoVo.setMatchType(false);
                }
                trackInfoVo.setPackLevel(1);
                break;
            case "H":
                if (partOne > trackFabricVo.getCaseNum()) {
                    return false;
                }
                if (partTwo > trackFabricVo.getBoxNum()) {
                    return false;
                }
                if (!partThr.equals(trackFabricVo.getPackNum())) {
                    return false;
                } else if (partThr != 0) {
                    trackInfoVo.setPackInfo(partThr + "包/盒");
                } else if (partOne == 0) {
                    trackInfoVo.setPackInfo(trackFabricVo.getProductSpecs());
                    trackInfoVo.setMatchType(false);
                } else {
                    trackInfoVo.setPackInfo(trackFabricVo.getProductSpecs());
                }
                trackInfoVo.setPackLevel(2);
                break;
            case "D":
                if (partOne > trackFabricVo.getCaseNum()) {
                    return false;
                }
                if (partTwo > trackFabricVo.getBoxNum()) {
                    return false;
                }
                if (partThr > trackFabricVo.getPackNum()) {
                    return false;
                }
                if (partTwo == 0) {
                    trackInfoVo.setMatchType(false);
                }
                trackInfoVo.setPackInfo(trackFabricVo.getProductSpecs());
                trackInfoVo.setPackLevel(3);
                break;
            default:
                return false;
        }
        return true;
    }

    private Integer chechNoticePolicy(TrackInfoVo trackInfoVo, NoticePolicy noticePolicy) {
        switch (noticePolicy.getPolicy()) {
            case 0:
                if (trackInfoVo.getPers() > noticePolicy.getDangerValue()) {
                    return 3;
                } else if (trackInfoVo.getPers() > noticePolicy.getWarningValue()) {
                    return 2;
                } else {
                    return 1;
                }
            case 1:
                return 1;
            default:
                return 1;
        }
    }

    public Message trackEan(QueryDto queryDto) {
        GsVo gsVo = new GsVo();
        gsVo.setType(queryDto.getType());
        Integer userId = 0;
        WxUser user = null;
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("MMM d yyyy HH:mm:ss:SSSa", Locale.ENGLISH);
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy年MM月dd日");
        //1.判断是否有openid或者伪id，二者皆无，创建伪id，保存新用户对象，并返回伪id，二者有一，查出userId
        if (StringUtils.isBlank(queryDto.getOpenid()) && StringUtils.isBlank(queryDto.getProvisionalId())) {
            user = new WxUser();
            String provisionalId = queryDto.getItemNo() + UUID.randomUUID().toString();
            user.setProvisionalId(provisionalId);
            wxUserRepository.save(user);
            userId = user.getUserId();
            gsVo.setProvisionalId(provisionalId);
        } else {
            user = wxUserRepository.findByProvisionalId(queryDto.getProvisionalId());
            userId = user.getUserId();
            gsVo.setProvisionalId(user.getProvisionalId());
        }
        GsOne gsOne = gsOneRepository.findByGtin(queryDto.getItemNo());
        GS1Result gs1Result = null;
        JSONObject jsonObject = null;
        if (null == gsOne || (gsOne.getValidState() == 1 || gsOne.getExpiredTime().compareTo(new Date()) < 0)) {
            if (null == gsOne) {
                gsOne = new GsOne();
                gsOne.setGtin(queryDto.getItemNo());
            }
            gs1Result = GS1Utils.getGS1Info(queryDto.getItemNo());
            if (gs1Result.getCode() == 0) {
                Integer validState = null;
                Date validDate = null;
                for (StringAVP s :
                        ((TSDBasicProductInformationModule) gs1Result.getResponse().getProductData().getProductDataRecord().get("TSDBasicProductInformationModuleType")).getPackagingSignatureLine().getAvpList()) {
                    if ("logout_flag".equals(s.getName())) {
                        validState = Integer.parseInt(s.getContent());
                    }
                    if ("valid_date".equals(s.getName())) {
                        try {
                            validDate = sdf2.parse(s.getContent());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if (null == validState) {
                    validState = 0;
                }
                gsOne.setValidState(validState);
                gsOne.setExpiredTime(validDate);
                gsOne.setContent(JSON.toJSONString(gs1Result));
                gsOneRepository.save(gsOne);
            } else {
                return new Message(1, gsVo);
            }
        } else {
            jsonObject = JSON.parseObject(gsOne.getContent()).getJSONObject("response").getJSONObject("productData").getJSONObject("productDataRecord").getJSONObject("TSDBasicProductInformationModuleType");
            gs1Result = JSON.parseObject(gsOne.getContent(), GS1Result.class);
        }
        TSDBasicProductInformationModule module = null;
        if (null == jsonObject) {
            module = (TSDBasicProductInformationModule) (gs1Result.getResponse().getProductData().getProductDataRecord().get("TSDBasicProductInformationModuleType"));
        } else {
            module = JSON.parseObject(jsonObject.toJSONString(), TSDBasicProductInformationModule.class);
        }

        //        WxRecord record = new WxRecord();
//        record.setRecordCode(queryDto.getItemNo());
//        record.setProductName(module.getProductName().getString());
//        record.setAddress(queryDto.getAddress());
//        record.setQueryTime(queryDto.getQueryTime());
//        record.setCollected(0);
//        user.getRecords().add(record);
//        wxUserRepository.save(user);
        GsProductVo productVo = new GsProductVo();
        productVo.setGtin(queryDto.getItemNo());
        if (!StringUtils.isBlank(module.getBrandNameInformation().getBrandName())) {
            productVo.setBrandName(module.getBrandNameInformation().getBrandName());
        }
        productVo.setProductName(module.getProductName().getString());
        if (null != module.getAvpList()) {
            for (StringAVP s :
                    module.getAvpList()) {
                productVo.getOthers().put(s.getName(), s.getContent());
            }
        }
        gsVo.setProduct(productVo);
        GsCompanyVo company = new GsCompanyVo();
        company.setCompanyName(module.getPackagingSignatureLine().getPartyContactName());
        company.setCompanyAddress(module.getPackagingSignatureLine().getPartyContactAddress());
        if (null != module.getProductInformationLink()) {
            company.setCodeWebsite(module.getProductInformationLink().getUrl());
        }
        Integer checkResult = null;
        Date logoutDate = null;
        String codeState = null;
        for (StringAVP s :
                module.getPackagingSignatureLine().getAvpList()) {
            if ("checkResult".equals(s.getName())) {
                checkResult = Integer.parseInt(s.getContent());
            }
            if ("logout_date".equals(s.getName())) {
                try {
                    logoutDate = sdf2.parse(s.getContent());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (StringUtils.isBlank(s.getName())) {
                if (StringUtils.isBlank(codeState)) {
                    codeState = s.getContent();
                }
            }
        }
        if (3 == checkResult) {
            codeState = "该企业已于" + sdf3.format(logoutDate) + "注销";
        }
        company.setCodeState(codeState);
        gsVo.setCompany(company);
        for (Link l :
                module.getImageLinks()) {
            gsVo.getPics().add(l.getUrl());
        }
        return new Message(0, gsVo);
    }

    @Override
    public Boolean match(String qr1, String qr2) {
        log.info("src qr1 is {} , src qr2 is {}", qr1, qr2);
        if (qr2.contains(QRCODE_PREFIX)) {
            qr2 = qr2.substring(qr2.indexOf(QRCODE_PREFIX) + QRCODE_PREFIX.length());
        }
        if (!qr1.substring(0, 34).equals(qr2.substring(0, 34))) {
            return false;
        }
        String batchKey = qr2.substring(0, 34);
        BatchVo batch = fabricDao.query("GetSomeCommInfo", batchKey, BatchVo.class);
        if (null == batch) {
            return false;
        }
        //1.拆解二维码
        String picLevel1 = qr1.substring(34, 35);
        String serial1 = qr1.substring(35);
        //2.解密序列号
        String trueSerial1 = SboxCreator.decrypt(serial1, batch.getSecretKey());
        Integer partOne1 = TsStringCreator.parseString(trueSerial1.substring(0,5),5);
        Integer partTwo1 = TsStringCreator.parseString(trueSerial1.substring(5,10),5);
        Integer partThr1 = TsStringCreator.parseString(trueSerial1.substring(10),5);
        //1.拆解二维码
        String picLevel2 = qr2.substring(34, 35);
        String serial2 = qr2.substring(35);
        //2.解密序列号
        String trueSerial2 = SboxCreator.decrypt(serial2, batch.getSecretKey());
        Integer partOne2 = TsStringCreator.parseString(trueSerial2.substring(0,5),5);
        Integer partTwo2 = TsStringCreator.parseString(trueSerial2.substring(5,10),5);
        Integer partThr2 = TsStringCreator.parseString(trueSerial2.substring(10),5);
        log.info("qr1 is {} {} {}, qr 2 is {} {} {}", partOne1, partTwo1, partThr1, partOne2, partTwo2, partThr2);
        switch (picLevel2) {
            case "X":
                return partOne2 == 0 &&
                        partTwo2 <= batch.getCaseNum() &&
                        (partThr2.equals(batch.getBoxNum())) &&
                        ("H".equals(picLevel1) || "D".equals(picLevel1)) &&
                        partOne1.equals(partTwo2);
            case "H":
                return partOne2 <= batch.getCaseNum() &&
                        partTwo2 <= batch.getBoxNum() &&
                        (partThr2.equals(batch.getPackNum())) &&
                        ("X".equals(picLevel1) || "D".equals(picLevel1)) &&
                        ("X".equals(picLevel1) ?
                                partOne2.equals(partTwo1) : (partOne1.equals(partOne2) && partTwo1.equals(partTwo2))
                                );
            case "D":
                return partOne2 <= batch.getCaseNum() &&
                        partTwo2 <= batch.getBoxNum() &&
                        partThr2 <= batch.getPackNum() &&
                        ("X".equals(picLevel1) || "H".equals(picLevel1)) &&
                        ("X".equals(picLevel1) ?
                                partOne2.equals(partTwo1) : (partOne1.equals(partOne2) && partTwo1.equals(partTwo2))
                        );
            default:
                return false;
        }
    }



}
